"""
需求相关数据模型
用于数据库存储的模型定义
"""
from datetime import datetime
from typing import List, Optional, TYPE_CHECKING
from enum import Enum
from pydantic import BaseModel, Field, validator
from bson import ObjectId
from app.models.base import PyObjectId

if TYPE_CHECKING:
    from app.schemas.requirement import RequirementComment, RequirementAttachment, RequirementDependency

# 需求状态通过state模块进行管理，使用字符串类型

class RequirementPriority(str, Enum):
    """需求优先级"""
    LOW = "low"          # 低
    MEDIUM = "medium"    # 中
    HIGH = "high"        # 高
    CRITICAL = "critical" # 严重

# RequirementType 和 RequirementSource 已移除，改为使用统一配置管理
# 类型和来源现在通过 types 和 sources 集合进行管理

class RequirementBase(BaseModel):
    """需求基础模型"""
    title: str = Field(..., min_length=1, max_length=200, description="需求标题")
    description: Optional[str] = Field(None, max_length=100000, description="需求描述")
    requirement_type: str = Field(default="functional", description="需求类型（从类型管理获取）")
    status: str = Field(default="", description="需求状态（从状态管理系统动态获取，创建时使用默认状态）")
    priority: RequirementPriority = Field(default=RequirementPriority.MEDIUM, description="需求优先级")
    source: str = Field(default="internal", description="需求来源（从来源管理获取）")
    project_id: PyObjectId = Field(..., description="所属项目ID")
    assignee_id: Optional[PyObjectId] = Field(None, description="负责人ID")
    reporter_id: PyObjectId = Field(..., description="报告人ID")
    acceptance_criteria: Optional[str] = Field(None, max_length=5000, description="验收标准")
    business_value: Optional[str] = Field(None, max_length=2000, description="业务价值")
    estimated_effort: Optional[float] = Field(None, ge=0, description="预估工作量(人天)")
    actual_effort: Optional[float] = Field(None, ge=0, description="实际工作量(人天)")
    start_date: Optional[datetime] = Field(None, description="开始日期")
    due_date: Optional[datetime] = Field(None, description="截止日期")
    tags: List[str] = Field(default_factory=list, description="需求标签")
    parent_id: Optional[PyObjectId] = Field(None, description="父需求ID，用于构建树形结构")
    sort_order: int = Field(default=0, description="排序顺序")
    
    @validator('due_date')
    def validate_due_date(cls, v, values):
        if v and 'start_date' in values and values['start_date'] and v < values['start_date']:
            raise ValueError('截止日期不能早于开始日期')
        return v

class RequirementInDB(RequirementBase):
    """数据库中的需求模型"""
    id: PyObjectId = Field(default_factory=PyObjectId, alias="_id")
    # 使用字符串类型避免循环导入，实际使用时从 schemas 导入
    comments: List[dict] = Field(default_factory=list, description="需求评论")
    attachments: List[dict] = Field(default_factory=list, description="需求附件")
    dependencies: List[dict] = Field(default_factory=list, description="需求依赖")
    watchers: List[PyObjectId] = Field(default_factory=list, description="关注者ID列表")
    created_at: datetime = Field(default_factory=datetime.utcnow, description="创建时间")
    updated_at: datetime = Field(default_factory=datetime.utcnow, description="更新时间")
    approved_at: Optional[datetime] = Field(None, description="批准时间")
    implemented_at: Optional[datetime] = Field(None, description="实现时间")
    
    class Config:
        populate_by_name = True
        arbitrary_types_allowed = True
        json_encoders = {ObjectId: str}

class Requirement(RequirementInDB):
    """需求模型"""
    pass